package com.java.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.entity.vo.WeChatAddDraftRequest;
import com.java.entity.vo.WeChatAddDraftResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class WeChatDraftService {

    private static final String ADD_DRAFT_URL = "https://api.weixin.qq.com/cgi-bin/draft/add?access_token=%s";

    /**
     * 添加草稿接口
     * @param accessToken 公众号access_token
     * @param req 业务封装VO
     * @return Draft接口响应
     */
    public WeChatAddDraftResponse addDraft(String accessToken, WeChatAddDraftRequest req) {
        log.info("上传素材入参: {}", req);

        RestTemplate restTemplate = new RestTemplate();
        String url = String.format(ADD_DRAFT_URL, accessToken);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<WeChatAddDraftRequest> entity = new HttpEntity<>(req, headers);

        try {
            ResponseEntity<String> resp = restTemplate.postForEntity(
                    url, entity, String.class); //  <---  关键修改： 接收 String

            if (resp.getStatusCode() == HttpStatus.OK) {
                // 尝试将 String 转换为 WeChatAddDraftResponse
                try {
                    //  **重要：**  这里假设微信在成功时 *仍然* 返回 JSON，只是错误时返回 text/plain
                    //  如果成功时也返回 text/plain，你需要修改这里的逻辑
                    WeChatAddDraftResponse successResponse = new ObjectMapper().readValue(resp.getBody(), WeChatAddDraftResponse.class);
                    log.info("上传素材成功, 响应: {}", successResponse);
                    return successResponse;

                } catch (JsonProcessingException e) {
                    // 如果 JSON 解析失败，说明微信返回的可能不是 JSON，记录错误
                    log.error("上传素材成功，但响应不是有效的 JSON: {}", resp.getBody(), e);
                    throw new RuntimeException("上传素材成功，但响应不是有效的 JSON: " + resp.getBody());
                }

            } else {
                log.error("上传素材失败, 状态码: {}, 响应: {}", resp.getStatusCode(), resp.getBody());
                throw new RuntimeException("上传素材失败，状态码: " + resp.getStatusCode() + ", 响应: " + resp.getBody());
            }
        } catch (RestClientException e) {
            log.error("上传素材发生异常: ", e);
            throw new RuntimeException("上传素材发生异常: " + e.getMessage());
        }
    }
}